import React from 'react';
import { Breadcrumb, Icon, Table, Button, Modal, Form, Input, Upload, message, Col, Carousel, Row } from 'antd';
import './recommend.less';
import $ from 'jquery';
import Config from '../../common/config';
import Recommendproduct from './recommendproduct';

const config = new Config();
const FormItem = Form.Item;
const { TextArea } = Input;
const token = sessionStorage.getItem('token')

//楼层信息的表单
const RecommendForm = Form.create()(
    (props) => {
        const { form, normFile, beforeUpload, fileList, previewImg } = props;
        const { getFieldDecorator } = form;
        const formItemLayout = { labelCol: { span: 2 }, wrapperCol: { span: 6 }, };
        return (
            <Form layout="vertical">
                <FormItem {...formItemLayout} label="活动名称" hasFeedback style={{ minHeight: '70px', marginBottom: 0 }}>
                    {getFieldDecorator('recommendname', {
                        rules: [{ required: true, max: 10, message: '请输入活动名称，不超过10个字' }],
                    })(
                        <Input type="text" placeholder="请输入活动名称" />
                    )}
                </FormItem>
                {/* <FormItem {...formItemLayout} label="主题图片" style={{ minHeight: '120px', marginBottom: 0 }}>
                    {getFieldDecorator('Filedata', {
                        valuePropName: 'fileList', getValueFromEvent: normFile,
                        rules: [{ required: true, message: '请上传主题图片' }],
                    })(
                        <Upload
                            accept="image/*"
                            name="img"
                            action={config.wx_homePage + "/uploadimg/img"}
                            beforeUpload={beforeUpload}
                            listType="picture-card"
                            className="upload-list-inline"
                            onPreview={previewImg}
                        >
                            {
                                fileList.length >= 1 ? null :
                                    <div>
                                        <Icon type="plus" />
                                        <div className="ant-upload-text">点击上传图片</div>
                                    </div>
                            }
                        </Upload>
                        )}
                </FormItem> */}
            </Form>
        );
    }
);
export default class Recommend extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            fileList: [],
            previewVisible: false,
            previewImage: '',
            productvisible: false,
            products: [],
            dataState: '',//数据状态
            preView: false,//首页预览模态框
            bannerList: [],//轮播图
            recommend: null,//商品推荐
            floor: [],//楼层管理
        }
    }
    componentDidMount() {
        this.getRecommendList();
        this.dataState();
    }
    //加载推荐信息
    getRecommendList() {
        $.ajax({
            url: `${config.JuseHomepage}/recommendApp/getone`,
            type: "get",
            headers: {
                Authorization: 'Bearer ' + token,
            },
            success: res => {
                console.log('加载推荐信息', res)
                if (res.code === 200) {
                    if (res.data) {
                        const { fileList } = this.state;
                        fileList.push({
                            uid: -1,
                            name: res.data.imgname,
                            status: 'done',
                            url: config.Filepath + res.data.imgname
                        });
                        this.recommendForm.setFieldsValue({
                            recommendname: res.data.recommendname,
                            // Filedata: fileList
                        });
                        const products = [];
                        for (let val of res.data.products) {
                            products.push(val)
                        }
                        this.setState({
                            products,
                            // fileList
                        })
                    } else {
                        this.recommendForm.setFieldsValue({
                            recommendname: "",
                            // Filedata: []
                        });
                        this.setState({
                            products: [],
                            // fileList: []
                        })
                    }
                } else {
                    message.error('推荐商品信息加载失败，请返回重新操作', 2);
                }
            }
        });
    }
    // //限制用户必须上传图片格式的文件、图片大小
    // beforeUpload(file, fileList) {
    //     let isIMG = file.type.indexOf('image') != -1;
    //     if (!isIMG) {
    //         message.config({ top: 50 });
    //         message.error('您只能上传图片！');
    //     }
    //     let isLt10M = file.size / 1024 / 1024 < 10;
    //     if (!isLt10M) {
    //         message.config({ top: 50 });
    //         message.error('您上传的图片大小必须小于10MB！');
    //     }
    //     return isIMG && isLt10M;
    // }
    // //上传图片
    // normFile(e) {
    //     this.setState({
    //         fileList: e.fileList
    //     });
    //     if (Array.isArray(e)) {
    //         return e;
    //     }
    //     return e && e.fileList;
    // };
    //获取表单元素
    saveRecommendFormRef(form) {
        this.recommendForm = form;
    }
    // //预览图片对话框
    // previewImg(file) {
    //     this.setState({
    //         previewImage: file.url || file.thumbUrl,
    //         previewVisible: true,
    //     });
    // }
    // //关闭预览图片对话框
    // cancelPreview() {
    //     this.setState({ previewVisible: false })
    // }
    //保存
    saveRecommend() {
        this.recommendForm.validateFields((err, values) => {
            if (!err) {
                const { products } = this.state;
                let productids = [];
                for (let val of products) {
                    if (val) {
                        productids.push(val.productId)
                    }
                }
                if (productids.length == 4 || productids.length == 8) {
                    $.ajax({
                        url: `${config.JuseHomepage}/recommendApp/save`,
                        type: "post",
                        headers: {
                            Authorization: 'Bearer ' + token,
                        },
                        data: {
                            recommendname: values.recommendname,
                            // imgname: values.Filedata[0].response ? values.Filedata[0].response.data : values.Filedata[0].name,
                            productids: productids.toString()
                        },
                        success: res => {
                            if (res.code === 200) {
                                this.setState({
                                    dataState: "数据未同步"
                                })
                                message.success('保存推荐商品信息成功！', 2);
                            } else {
                                Modal.warning({
                                    title: '保存失败',
                                    content: `${res.mes}请返回重新操作`,
                                });
                            }
                        }
                    });
                } else {
                    Modal.warning({
                        title: '保存失败',
                        content: `楼层必须包含4(或8)个展示商品！`,
                    });
                }
            } else {
                Modal.warning({
                    title: '保存失败',
                    content: `请填写必要的信息，再提交`,
                });
            }
        })
    }
    //添加商品的对话框组件
    addProductModal() {
        const { products } = this.state;
        if (this.state.products.length >= 8) {
            message.error('添加商品数已达到上限8个，请先删除再添加', 2);
        } else {
            this.setState({
                productvisible: true,
            })
        }
    }
    //确认添加商品
    addProduct(products) {
        this.setState({
            productvisible: false,
            products
        })
    }
    //取消添加商品
    cancelProduct() {
        this.setState({
            productvisible: false
        })
    }
    //移动商品
    moveProduct(index, toindex) {
        const { products } = this.state;
        const item = products[index];
        products[index] = products[toindex];
        products[toindex] = item;
        this.setState({
            products
        })
    }
    //删除商品
    deleteProduct(index) {
        const { products } = this.state;
        products.splice(index, 1)
        this.setState({
            products
        })
    }
    //同步数据状态
    dataState() {
        $.ajax({
            url: config.JuseHomepage + '/sync/dataState',
            type: 'GET',
            traditional: true,
            dataType: 'json',
            headers: {
                Authorization: 'Bearer ' + token,
            },
            success: (data) => {
                if (data.code === 200) {
                    this.setState({
                        dataState: data.mes
                    });
                } else {
                    this.setState({
                        dataState: '请求失败'
                    });
                }
            },
        })
    }
    //首页生成
    sync() {
        $.ajax({
            url: config.JuseHomepage + '/sync/sync',
            type: 'POST',
            traditional: true,
            dataType: 'json',
            headers: {
                Authorization: 'Bearer ' + token,
            },
        }).then(data => {
            if (data.code === 200) {
                message.info("同步成功")
                this.setState({
                    dataState: "数据已同步"
                })
            } else {
                message.info(data.mes)
            }
        })
    }
    //首页预览
    preView() {
        this.setState({ preView: true })
        $.ajax({
            url: config.JuseHomepage + '/sync/home',
            type: 'GET',
            traditional: true,
            dataType: 'json',
            headers: {
                Authorization: 'Bearer ' + token,
            },
        }).then(data => {
            if (data.code === 200) {
                this.setState({
                    bannerList: data.banner,
                    recommend: data.recommend,
                    floor: data.floor
                })
            } else {
                message.info(data.mes)
            }
        })
    }
    //取消首页预览
    preViewCancel() {
        console.log(1)
        this.setState({
            preView: false
        })
        console.log(this.state.preView)
    }
    render() {
        return (
            <div className='goods-label zwq_recommendclass'>
                <div className='goods-label-cont clearfix'>
                    <div className='goods-label-cont-nav clearfix'>
                        <Breadcrumb separator=">">
                            <Breadcrumb.Item>首页管理</Breadcrumb.Item>
                            <Breadcrumb.Item>推荐管理</Breadcrumb.Item>
                        </Breadcrumb>
                    </div>
                    <div style={{ marginBottom: '20px', float:'left', width:'100%'}}>
                        <Col span={6}>
                            <Button.Group size="default" >
                                <Button icon="search" style={{ height: '40px' }} onClick={this.preView.bind(this)}>首页预览</Button>
                                <Button style={{ height: '40px' }} onClick={this.sync.bind(this)}>首页生成</Button>
                            </Button.Group>
                        </Col>
                        <Col span={4}>
                            <div style={{ height: 28, lineHeight: '28px' }}> 数据状态:&nbsp;&nbsp;&nbsp;<span style={this.state.dataState == "数据已同步" ? { color: "green" } : { color: "red" }}>{this.state.dataState}</span></div>
                        </Col>
                        <Button onClick={this.saveRecommend.bind(this)} className="floor-savebtn">保存</Button>
                    </div>
                    <div className='allgoods-table clearfix'>
                        <div className="floor-msg recmmend-msg">
                            {/* 楼层信息表单 */}
                            <RecommendForm
                                ref={this.saveRecommendFormRef.bind(this)}
                            // normFile={this.normFile.bind(this)}
                            // beforeUpload={this.beforeUpload.bind(this)}
                            // fileList={this.state.fileList}
                            // previewImg={this.previewImg.bind(this)}
                            />
                            {/* 预览图片对话框 */}
                            {/* <Modal visible={this.state.previewVisible} footer={null} onCancel={this.cancelPreview.bind(this)}>
                                <img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
                            </Modal> */}

                            <div className="zwq_floor-products">
                                <p style={{ fontSize: "16px", marginBottom: "5px", marginLeft: "1%" }}>添加商品<Button className='floor-addbtn' width={160} icon="plus" onClick={this.addProductModal.bind(this)}></Button></p>
                                <ul>
                                    {
                                        this.state.products.map((item, index) => {
                                          if(item){
                                            return (<Col span={4} key={index}><li style={{ textAlign: 'center' }}>
                                                <a href={item.imageUrl + item.listImage + '?x-oss-process=image/resize,m_fixed,h_400,w_400'} target='_blank'>
                                                    <img src={item.imageUrl + item.listImage + '?x-oss-process=image/resize,m_fixed,h_200,w_200'} />
                                                </a>
                                                <p>{item.productname}</p>
                                                <div className="floor-pmove">
                                                    {index > 0 && <a onClick={this.moveProduct.bind(this, index, index - 1)} style={{ marginRight: "6%" }}><Icon type="arrow-up" />上移</a>}
                                                    {index < this.state.products.length - 1 && <a onClick={this.moveProduct.bind(this, index, index + 1)} style={{ marginRight: "6%" }}><Icon type="arrow-down" />下移</a>}
                                                    <a onClick={this.deleteProduct.bind(this, index)}><Icon type="close" />删除</a>
                                                </div>
                                            </li></Col>)
                                          }
                                        })
                                    }

                                </ul>
                                <Recommendproduct
                                    visible={this.state.productvisible}
                                    products={this.state.products}
                                    addProduct={this.addProduct.bind(this)}
                                    cancelProduct={this.cancelProduct.bind(this)}
                                />
                            </div>
                        </div>
                    </div>
                </div>
                {/* 首页预览 */}
                <Modal visible={this.state.preView} onCancel={this.preViewCancel.bind(this)} footer={null} className='preViewModel'>
                    <div>
                        <div>
                            <Input.Search placeholder="999感冒灵">
                            </Input.Search>
                            {/* 轮播 */}
                            <Carousel autoplay dots={false}>
                                {
                                    this.state.bannerList.map((value, index) => {
                                        return <div key={index}>
                                            <div>
                                                <a href={value.linkAdress} target="_blank">
                                                    <img src={`${config.Filepath}${value.imgAdress}`} style={{ width: '100%' }} />
                                                </a>
                                            </div>
                                        </div>
                                    })
                                }
                            </Carousel>
                            {/* 推荐 */}
                            {
                                this.state.recommend ?
                                    (<div>
                                        <p style={{ textAlign: 'center', fontWeight: '600', marginTop: 20, marginBottom: 20, fontSize: 14 }}>{this.state.recommend.recommendname}</p>
                                        {this.state.recommend.products.map((value, index) => {
                                            return (<Col span={8} key={index}>
                                                <div style={{ textAlign: 'center' }} >
                                                    <img src={`${value.imageUrl}${value.listImage}?x-oss-process=image/resize,m_fixed,h_100,w_100`} style={{ width: '80%' }} />
                                                </div>
                                                <p style={{ textAlign: 'center' }}>{value.genericName}</p>
                                                <p style={{ textAlign: 'center', color: 'red', fontWeight: '600' }}>{value.marketPrice}</p>
                                            </Col>)
                                        })}
                                    </div>)
                                    : ''
                            }
                        </div>
                        <p style={{ position: 'relative', background: '#aaa', lineHeight: '16px', textAlign: 'center', top: -70 }}>下拉加载更多</p>
                        {/* 楼层 */}
                        <div style={{ minHeight: 630 }}>
                            {
                                this.state.floor.map((value, index) => {
                                    return (<Row key={index} style={{ marginBottom: 10 }}>
                                        <p style={{ textAlign: 'center', fontWeight: '600', marginTop: 10, marginBottom: 10, fontSize: 14 }}>{value.floorname}</p>
                                        <p style={{ textAlign: 'center', marginBottom: 10 }}>{value.floorname}</p>
                                        <Col span={24} style={{ marginBottom: 10 }} >
                                            <a href={value.link} target="_blank">
                                                <div style={{ textAlign: 'center' }} >
                                                    <img src={`${config.Filepath}${value.imgname}`} style={{ width: '90%', maxHeight: 170 }} />
                                                </div>
                                            </a>
                                        </Col>
                                        {value.floorproducts.map((value, index) => {
                                            return (<Col span={8} key={index + 'a'}>
                                                <div style={{ textAlign: 'center' }} >
                                                    <img src={`${value.imageUrl}${value.listImage}?x-oss-process=image/resize,m_fixed,h_100,w_100`} style={{ width: '90%' }} />
                                                </div>
                                                <p style={{ textAlign: 'center' }}>{value.genericName}</p>
                                                <p style={{ textAlign: 'center', color: 'red', fontWeight: '600' }}>{value.marketPrice}</p>
                                            </Col>)
                                        })}
                                    </Row>)
                                })
                            }
                        </div>
                        <div style={{ height: 62, width: 370, backgroundColor: '#fff', position: 'absolute', bottom: 20, left: 20 }}>
                            <img src='src/images/footer.png' style={{ width: 348 }} />
                        </div>
                    </div>
                </Modal>
            </div>
        )
    }
}